package cn.quevo.core.file;

import cn.quevo.core.file.enums.ImageCodeType;
import cn.quevo.core.file.entity.WriteImage;
import cn.quevo.core.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;

/**
 * 图片工具类
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2018-03-09 15:30:36
 * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
 * @return
 */
public class ImagesUtil {
    private final static Logger log = LoggerFactory.getLogger(ImagesUtil.class);

    /**
     * 根据URL获取图片大小
     *
     * @param url
     * @return
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 15:30:49
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static Images getImages(String url) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        String _url = url.toLowerCase();
        try {
            if (_url.startsWith("/") || _url.startsWith("file")) {
                return getImagesByLocal(url);
            }
            return getImagesByURL(_url);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 网络图片
     *
     * @param url
     * @return
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 15:30:56
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static Images getImagesByURL(String url) throws IOException {
        URLConnection conn = new URL(url).openConnection();
        if (!conn.getContentType().startsWith("image")) {
            return null;
        }
        Images images = new Images();
        images.setImgSize(conn.getContentLengthLong());
        images.setImgPath(url);
        BufferedImage img = ImageIO.read(conn.getInputStream());
        images.setWidth(img.getWidth());
        images.setHeight(img.getHeight());
        return images;
    }

    /**
     * 本地图片
     *
     * @param file
     * @return
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 15:31:12
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static Images getImagesByLocal(String file) throws IOException {
        Path path = Paths.get(file);
        if (!Files.exists(path)) {
            return null;
        }
        Images images = new Images();
        images.setImgSize(path.toFile().length());
        images.setImgPath(file);
        BufferedImage img = ImageIO.read(path.toFile());
        images.setWidth(img.getWidth());
        images.setHeight(img.getHeight());
        return images;
    }

    /**
     * 图片流
     *
     * @param stream
     * @return
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 15:31:20
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static Images getImagesByInputStream(InputStream stream) throws IOException {
        if (stream == null) {
            return null;
        }
        Images images = new Images();
        images.setImgSize(stream.available() * 1L);
        BufferedImage img = ImageIO.read(stream);
        images.setWidth(img.getWidth());
        images.setHeight(img.getHeight());
        return images;
    }

    /**
     * 生成Image
     *
     * @param writeImage
     * @return
     * @author July july_sky@foxmail.com
     * @date 2018-05-13 09:13:03
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static BufferedImage createBufferdImage(WriteImage writeImage) {
        if (writeImage == null || StringUtils.isBlank(writeImage.getWidth(), 1) || StringUtils.isBlank(writeImage.getHeight(), 1) || StringUtils.isBlank(writeImage.getText())) {
            return null;
        }
        // 定义图像buffer
        BufferedImage buffImg = new BufferedImage(writeImage.getWidth(), writeImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D gd = buffImg.createGraphics();
        // 设置底色
        gd.setColor(writeImage.getBackageColor() != null ? writeImage.getBackageColor() : new Color(0, 0, 0, 0));
        gd.fillRect(0, 0, writeImage.getWidth(), writeImage.getHeight());
        // 创建字体，字体的大小应该根据图片的高度来定。
        Font font = new Font(StringUtils.isBlank(writeImage.getFontName()) ? writeImage.getFontName() : "微软雅黑",
                writeImage.getFontBlod() == null || writeImage.getFontBlod() ? Font.BOLD : Font.PLAIN,
                StringUtils.isBlank(writeImage.getFontSize(), 8) ? Double.valueOf(writeImage.getHeight() * 0.8).intValue() : writeImage.getFontSize());
        // 设置字体。
        gd.setFont(font);

        Random random = new Random();
        if (writeImage.getImageCodeType() != null) {
            writeImage.getImageCodeType().getValidateClass().draw(gd,writeImage);
        }
        // 验证码
        char[] codes = writeImage.getText().toCharArray();
        int x = (writeImage.getWidth()) / (codes.length+1);
        int top = StringUtils.isBlank(writeImage.getPaddingTop()) ? writeImage.getHeight() - font.getSize() : writeImage.getPaddingTop();
        int left = StringUtils.isBlank(writeImage.getPaddingLeft()) ? x / 2 : writeImage.getPaddingLeft();
        for (int i = 0; i < codes.length; i++) {
            // 用随机产生的颜色将验证码绘制到图像中。
            gd.setColor(new Color(random.nextInt(255 + 1), random.nextInt(255 + 1), random.nextInt(255 + 1)));
            gd.drawString(String.valueOf(codes[i]), i * x + left, font.getSize() + random.nextInt(top));
        }
        return buffImg;
    }
}
